<template>
    <div class="bottom-btn-common">
        <div class="bottom-btn-items" v-if="footerBar == 'index'">
            <img src="../static/img/images/house_b.png"/>
        </div>
        <div class="bottom-btn-items" v-else @click.stop="$router.push('/')">
            <img src="../static/img/images/house_g.png"/>
        </div>

        <div class="bottom-btn-items can-click" v-if="footerBar == 'chat'">
            <div class="message-chat">
                <div class="message-number" v-if="this.$store.state.store.chatMsgNumber">
                    {{this.$store.state.store.chatMsgNumber}}
                </div>
                <img src="../static/img/images/message_b.png"/>
            </div>
        </div>
        <div class="bottom-btn-items can-click" v-else @click.stop="showInboxAcvitiy()">
            <div class="message-chat">
                <div class="message-number" v-if="this.$store.state.store.chatMsgNumber">
                    {{this.$store.state.store.chatMsgNumber}}
                </div>
                <img src="../static/img/images/message_g.png"/>
            </div>
        </div>
        <!--<div class="bottom-btn-items can-click" v-if="footerBar == 'search'">-->
        <!--<img src="../static/img/images/search_b.png"/>-->
        <!--</div>-->
        <!--&lt;!&ndash;<div class="bottom-btn-items can-click" v-else @click="$router.push('/search/category')">&ndash;&gt;-->
        <!--<div class="bottom-btn-items can-click" v-else @click="$router.push('/buy-list')">-->
        <!--<img src="../static/img/images/search_g.png"/>-->
        <!--</div>-->

        <div class="bottom-btn-items center" @click.stop="$router.push('/category')">
            <div class="center-icon">
                <div class="icon-box">
                    <img slot="icon" src="../static/img/images/camera.png">
                </div>
            </div>
            <span>{{$t('m.Sell')}}</span>
        </div>

        <div class="bottom-btn-items can-click" v-if="footerBar == 'favourites'">
            <img src="../static/img/images/heart_b.png"/>
        </div>
        <div class="bottom-btn-items can-click" v-else @click.stop="$router.push('/user/favourites')">
            <img src="../static/img/images/heart_g.png"/>
        </div>

        <div class="bottom-btn-items can-click" v-if="footerBar == 'user'">
            <img src="../static/img/images/user_b.png"/>
        </div>
        <div class="bottom-btn-items can-click" v-else @click.stop="$router.push('/user/myaccount')">
            <img src="../static/img/images/user_g.png"/>
        </div>
    </div>
</template>
<script>
    import qs from 'qs'
    import {chatAppkey} from '../static/api/zxy_api';
    import {buyInformation} from '../static/api/mgc_api'


    export default {
        name: 'Footer',
        props: [
            'footerBar'
        ],
        data() {
            return {};
        },
        methods: {
            showInboxAcvitiy() {
                // this.$router.push({path:'/chat/chat',query: {fromType: 'index'}})
                // window.applozicSideBox.load()

                // 应用是否登录
                if (!this.$store.state.store.isLogin) {
                    this.$router.push('/login-register/loginregister')
                    return;
                }

                if(!this.$store.state.store.chatLoginStatus){
                    this.$toast({
                        mask: true,
                        forbidClick: true,
                        message: 'Loading...Please wait'
                    });
                }

                // 聊天是否登录
                if (this.$store.state.store.chatLoginStatus) {

                    if(window.android){  // 调用原生聊天列表
                        window.android.showConversation();
                        return;
                    }

                    if (window.$applozic) {

                        // 首先请求会话列表接口数据
                        this.$toast({
                            mask: true,
                            forbidClick: true,
                            message: 'loading...'
                        });

                        Applozic.ALApiService.getMessages({
                            data:
                                {
                                    startIndex: 0,
                                    mainPageSize: 60
                                },
                            success: (response) => {
                                this.$toast.clear();

                                console.log(response, '会话列表数据')
                                let res = qs.parse(response)
                                ALStorage.setLatestMessageArray(res.data.message);
                                window.$applozic.fn.applozic('loadTab', '');
                            },
                            error: () => {
                                this.$toast.clear();
                            }
                        });
                    }
                }

            },
            getCountChat() {
                if (!window.$applozic) {
                    return;
                }

                let userInfo = localStorage.getItem("userInfo") || '';
                userInfo = JSON.parse(userInfo) || '';

                if (!userInfo.id) {
                    return;
                }

                $.ajax({
                    url: "https://apps.applozic.com/rest/ws/user/v2/detail",
                    type: 'POST',
                    dataType: 'json',
                    data: JSON.stringify({userIdList: [userInfo.id]}),
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("Application-Key", `${chatAppkey}`);
                        xhr.setRequestHeader("Authorization", localStorage.getItem('Authorization'));
                        xhr.setRequestHeader("Device-Key", localStorage.getItem('Device-Key'));
                    },
                    contentType: 'application/json',
                    success: (res) => {
                        console.log(res, '未读res')
                        let num = res.response[0].unreadCount || '';

                        this.$store.commit('store/updateChatMsgNumber', num)
                    }
                });
            },
            chatLoginListen() {
                if (!window.$applozic) {
                    return;
                }
                window.$applozic.fn.applozic('subscribeToEvents', {
                    onConnect: function () {
                        //User subscribed successfully
                        // this.$store.state.store.chatLoginStatus !== 0
                        // this.$store.commit('store/updateChatLoginStatus', 'successfully')
                    },
                    onConnectFailed: function () {
                        //connection failed
                        // this.$store.commit('store/updateChatLoginStatus', 'failed')
                    },
                    onMessageDelivered: function (obj) {
                        //message delivered obj json: {'messageKey': 'delivered-message-key'}
                        // this.$store.commit('store/updateChatLoginStatus', 'message delivered')
                    },
                    onMessageRead: function (obj) {
                        //message read obj json: {'messageKey': 'read-message-key'}
                    },
                    onMessageReceived: (response) => {

                        console.log(response, '监听事件，收到消息的时候')

                        //message received
                        if (response.message.contentType !== 10 && response.message.contentType !== 102) {

                            //write your code to update unread count in UI
                            // 通过api查询当前的未读消息总数
                            this.getCountChat();
                        }
                    },
                    onMessageSent: function (obj) {
                        //message sent
                    },
                    onMessageSentUpdate: function (obj) {
                        //message sent confirmation: {'messageKey': 'sent-message-key'}
                    },
                    onMessageDeleted: function (obj) {
                        //message delete obj json : {'messageKey': 'deleted-message-key'}
                    },
                    onConversationDeleted: function (obj) {
                        //all messages deleted obj json : {'userId': userId}
                    },
                    onUserConnect: function (obj) {
                        //user from the contact list came online: {'userId': 'connected-user-Id'}
                        // this.$store.commit('store/updateChatLoginStatus', 'user from the contact')
                    },
                    onUserDisconnect: function (obj) {
                        //user from the contact list went offline: {'userId': 'connected-user-Id'}
                        // this.$store.commit('store/updateChatLoginStatus', 'disconnect')
                    },
                    onUserBlocked: function (obj) {
                        //user blocks someone or gets blocked by someone: {'status': 'BLOCKED_TO or BLOCKED_BY', 'userId': userId}
                    },
                    onUserUnblocked: function (obj) {
                        //user unblocks someone or get unblocked by someone: {'status': 'BLOCKED_TO or BLOCKED_BY', 'userId': userId}
                    },
                    onUserActivated: function () {
                        //user is activated by app admin
                    },
                    onUserDeactivated: function () {
                        //user is deactivated by app admin
                    }
                });
            },
            // 关闭按钮事件监听
            onClose() {
                let btn = document.getElementsByClassName('mck-box-close mck-close-sidebox move-right')[0];
                btn.addEventListener('click', () => {
                    // console.log('关闭聊天的时候，请求未读总数')
                    this.getCountChat();
                })
            },
            onToDetail() {
                let imgDom = document.getElementsByClassName('mck-product-icon')[0];
                imgDom.addEventListener('click', () => {
                    let idDomText = document.getElementsByClassName('mck-product-value')[1].innerText;
                    idDomText = idDomText.substr(1, idDomText.length);

                    console.log(idDomText, '获取主题中的id，跳转到该详情页面')
                    let mskSlideBox = document.getElementById('mck-sidebox')
                    mskSlideBox.style.display = 'none';

                    if (!idDomText) {
                        return;
                    }

                    this.$router.push({
                        path: '/buydetail',
                        query: {
                            id: idDomText
                        }
                    })
                })
            },
            getDetail(id) {
                buyInformation(id).then((res) => {
                    if (res.data.errorID === 0) {
                        if (res.data.object) {
                            let obj = res.data.object
                            let imgArr = obj.images.sort((a, b) => a.sequence - b.sequence);

                            this.$store.commit('store/updateSubjectDetail', {
                                show: true,
                                imgUrl: imgArr[0].url,
                                title: obj.title,
                                priceType: obj.priceType,
                                price: obj.price,
                                goodsId: obj.id
                            })

                        }
                    } else {
                        this.$toast(res.data.message)
                        this.finished = false
                        this.pageLoading = false
                    }
                }).catch((e) => {
                    console.log(e)
                    this.$toast('No internet, please try again')
                })
            },
        },
        mounted() {
            // 获取本地存储中的数据
            let userInfo = localStorage.getItem("userInfo") || '';
            if (userInfo) {
                userInfo = JSON.parse(userInfo) || '';
                // console.log(userInfo, window.applozic, '登录聊天之前的用户信息数据')

                // 切换到主页则获取未读数目
                this.getCountChat();

                if (!this.$store.state.store.chatLoginStatus) {
                    // 聊天系统插件下载
                    ((d, m) => {
                        // console.log('下载js,安装')
                        var s, h;
                        s = document.createElement("script");
                        s.type = "text/javascript";
                        s.async = true;
                        s.src = "https://apps.applozic.com/sidebox.app";
                        h = document.getElementsByTagName('head')[0];
                        h.appendChild(s);
                        window.applozic = m;
                        m.init = function (t) {
                            m._globals = t;
                        }
                        // console.log(this.$store.state.store.chatLoginStatus, window.applozic, '执行init聊天')
                        window.applozic.init({
                            // buyDetail 鉴权部分也要修改key
                            appId: `${chatAppkey}`,// zxykey:1879c84a74a848e2348d89995c72547d//Get your application key from https://www.applozic.com
                            userId: userInfo.id + "", //Logged in user's id, a unique identifier for user
                            userName: this.$store.state.store.localLang == 'MM' ? this.$translateLang(userInfo.name, 'unicodeTozawgyi') : userInfo.name, //User's display name
                            imageLink: userInfo.photo || 'https://www.tolymoly.com.mm/user-head.png', //User's profile picture url
                            desktopNotification: true,
                            source: "6", // optional, WEB(1),DESKTOP_BROWSER(5), MOBILE_BROWSER(6)
                            notificationIconLink: "https://www.applozic.com/favicon.ico", //Icon to show in desktop notification, replace with your icon
                            authenticationTypeId: 1, //1 for password verification from Applozic server and 0 for access Token verification from your server
                            locShare: true,
                            autoTypeSearchEnabled: true, // set to false if you don't want to allow sending message to user who is not in the contact list
                            loadOwnContacts: false, //set to true if you want to populate your own contact list (see Step 4 for reference)
                            topicBox: false,
                            onInit: (response, data) => {
                                console.log(response, '登录接口返回信息', data, 'data')
                                if (response === "success") {
                                    // login successful, perform your actions if any, for example: load contacts, getting unread message count, etc

                                    this.$store.commit('store/updateChatLoginStatus', true)


                                    // 判断是否为rn
                                    if(window.isRNWebView){
                                        let userInfo = {
                                            userId: data.userId || ''
                                        }
                                        window.postMessage(JSON.stringify(userInfo));
                                    } else if(window.android){
                                        window.android.loginIm(data.userId + '');
                                    }


                                    // Authorization
                                    let userId = data.userId;
                                    let deviceKey = data.deviceKey;

                                    let Authorization = window.btoa(userId + ':' + deviceKey);
                                    localStorage.setItem('Authorization', 'Basic ' + Authorization)
                                    localStorage.setItem('Device-Key', deviceKey)

                                    // window.$applozic.fn.applozic('loadTab', '');  // 新建组的时候清空session 不需要此步骤

                                    // 返回信息中提示的未读数目
                                    // this.$store.commit('store/updateChatMsgNumber', data.totalUnreadCount)
                                    // 通过api查询当前的未读消息总数
                                    this.getCountChat();

                                    // 登录之后做事件监听
                                    this.chatLoginListen();

                                } else {
                                    // error in user login/register (you can hide chat button or refresh page)
                                }
                            },
                            contactDisplayName: function (otherUserId) {
                                //return the display name of the user from your application code based on userId.
                                return "";
                            },
                            contactDisplayImage: function (otherUserId) {
                                //return the display image url of the user from your application code based on userId.
                                return "";
                            },
                            onTabClicked: (response) => {
                                // write your logic to execute task on tab load
                                //   object response =  {
                                //    tabId : userId or groupId,
                                //    isGroup : 'tab is group or not'
                                //  }

                                console.log(response, 'onTabClick')

                                let slideDom = document.getElementById('mck-sidebox');
                                slideDom.classList.add('mck-height')

                                this.$store.commit('store/updateSubjectDetail', {
                                    show: false,
                                    imgUrl: '',
                                    title: '',
                                    priceType: '',
                                    price: '',
                                    goodsId: ''
                                })

                                // 通过clientGoupId获取groupId
                                $.ajax({
                                    url: "https://apps.applozic.com/rest/ws/group/v2/info?groupId=" + response.tabId,
                                    type: 'Get',
                                    dataType: 'json',
                                    beforeSend: function (xhr) {
                                        xhr.setRequestHeader("Application-Key", `${chatAppkey}`);
                                        xhr.setRequestHeader("Authorization", localStorage.getItem('Authorization'));
                                        xhr.setRequestHeader("Device-Key", localStorage.getItem('Device-Key'));
                                    },
                                    contentType: 'application/json',
                                    success: (res) => {
                                        if (res.status == 'success') {
                                            let clientGroupId = res.response.clientGroupId;
                                            console.log(res, '获取到的groupId啊', '===', clientGroupId)
                                            let goodsId = clientGroupId.split(",")[0];
                                            console.log(goodsId, '当前的详情id')

                                            this.getDetail(goodsId);

                                        }
                                    }
                                });


                            }
                        });
                    })(document, window.applozic || {});

                    // setTimeout(() => {
                    //     this.onClose();
                    //     this.onToDetail();
                    // }, 5000)

                    // let bodyDom = document.getElementsByTagName('body')[0];
                    // bodyDom.addEventListener('click', function (e) {
                    //     console.log(e.target, '事件源')
                    //     return;
                    // })
                }

            }
        }
    }

</script>
<style scoped>
    .bottom-btn-common {
        display: flex;
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        height: 56px;
        line-height: 56px;
        background: #fff;
        border-top: 1px solid #e5e5e5;
    }

    .bottom-btn-items {
        width: 20%;
        text-align: center;
        padding: 9px 0;
    }

    .bottom-btn-items img {
        height: 38px;
        width: 41.3px;
    }

    .bottom-btn-items .icon-box img {
        width: 29px;
        height: 29px;
    }

    .bottom-btn-items.can-click:active {
        background: #e5e5e5;
    }

    .bottom-btn-items.center {
        position: relative;
    }

    .bottom-btn-items.center img {
        height: auto;
    }

    .bottom-btn-items.center span {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        line-height: 14px;
        font-size: 14px;

    }

    .bottom-btn-items.center .center-icon {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 16px;
    }

    .bottom-btn-items.center .icon-box {
        width: 55px;
        height: 55px;
        margin: 0 auto;
        background: #FF8820;
        padding-top: 8px;
        box-sizing: border-box;
        border-radius: 50%;
    }

    .message-chat {
        position: relative;
        display: inline-block;
        height: 38px;
        width: 41.3px;
    }

    .message-number {
        color: #fff;
        right: -5px;
        top: 1px;
        font-size: .6em;
        /*padding: 0 .5em;*/
        text-align: center;
        width: 1.4em;
        height: 1.4em;
        line-height: 1.4;
        position: absolute;
        border-radius: .6em;
        box-sizing: border-box;
        background-color: #f44;
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
        font-family: PingFang SC, Helvetica Neue, Arial, sans-serif;
    }
</style>
